<template>
  <div style="width: 100%;">
    <div class="plugin-content four-scroll-y" style="padding: 24px;">
      <a-table
        v-if="applyType === 'applied'"
        :custom-row="customRow"
        :columns="columns"
        :loading="tableLoading"
        :data-source="localPlugins"
        :pagination="false"
        row-key="id"
        class="my-table"
      >
        <span slot="name" slot-scope="text, record" class="title">
          <a-icon-font
            :type="record.type === 1 ? 'iconsuanfa1' : 'iconmoxing'"
            class="icon"
          ></a-icon-font
          >{{ record.name }}
        </span>
        <span slot="publicTime" slot-scope="text, record">
          {{ record.publicTime.split(' ')[0] }}
        </span>
        <span slot="action" slot-scope="record">
          <a @click.stop="uninstal(record)">卸载</a>
          <span v-if="record.numVersion > 1">
            <!-- <span> -->
            <a-divider type="vertical" />
            <a @click.stop="viewVisions(record)">其他版本</a>
          </span>
        </span>
        <div slot="expandedRowRender" slot-scope="record" class="cell-detail">
          <img class="icon" :src="record.cover ? record.cover : defaulCover" />
          <!-- <a-icon-font class="icon" :type="record.type===1?'iconsuanfa1':'iconmoxing'"></a-icon-font> -->
          {{ record.summary }}
        </div>
      </a-table>
      <a-table
        v-if="applyType === 'b'"
        :columns="columns2"
        :loading="tableLoading"
        :data-source="localPlugins"
        row-key="uid"
        :pagination="false"
        class="my-table"
      >
        <span slot="action" slot-scope="record">
          <a
            :disabled="record.installStatus !== '1'"
            @click.stop="uninstal(record)"
            >卸载</a
          >
        </span>
      </a-table>
      <a-pagination
        v-if="localPlugins.length > 0"
        v-model="pageIndex"
        class="pagination"
        align="right"
        :page-size.sync="pageSize"
        :default-current="1"
        :total="totalElements"
        show-size-changer
        show-quick-jumper
        show-less-items
        @change="pageChange"
        @showSizeChange="pageSizeChange"
      />
    </div>

    <vision-modal
      :id="viewId"
      :visible="visionVisible"
      title="其他版本"
      @cancel="visionVisible = false"
    />

    <un-install-modal
      :visible="uninstallVisible"
      :title="`无法卸载“${deleteItem.name}”！`"
      :project-ids="projects"
      :type="deleteItem.type"
      @cancel="uninstallVisible = false"
    />
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import VisionModal from '@/components/plugin/VisionModal.vue'
import UnInstallModal from '@/components/plugin/UnInstallModal.vue'
import DataViewStore from '@/store/modules/dataview'
import {
  queryLocalModel,
  queryProjectUsed,
  deleteLocalModel,
} from '@/api/plugin'

@Component({
  components: { VisionModal, UnInstallModal },
})
export default class PluginHome extends Vue {
  @Prop() field!: string
  @Prop() tab!: string
  @Prop() whereValue!: string
  public columns = [
    {
      title: '模型/算法',
      key: 'name',
      dataIndex: 'name',
      scopedSlots: { customRender: 'name' },
      sorter: (a: { name: string }, b: { name: string }) =>
        `${a.name}` > `${b.name}` ? 1 : -1,
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '创建者',
      key: 'owner',
      dataIndex: 'owner',
      scopedSlots: { customRender: 'owner' },
      sorter: (a: { owner: string }, b: { owner: string }) =>
        a.owner > b.owner ? 1 : -1,
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '发布时间',
      dataIndex: 'publicTime',
      key: 'publicTime',
      defaultSortOrder: 'descend',
      sorter: (a: { publicTime: string }, b: { publicTime: string }) =>
        Date.parse(a.publicTime) - Date.parse(b.publicTime),
    },
    {
      title: '关键词',
      key: 'keyword',
      dataIndex: 'keyword',
      scopedSlots: { customRender: 'keyword' },
    },
    {
      title: '操作',
      key: 'operate',
      scopedSlots: { customRender: 'action' },
    },
  ]
  public columns2 = [
    {
      title: '名称',
      key: 'owner',
      dataIndex: 'owner',
      scopedSlots: { customRender: 'owner' },
      // sorter: (a: { owner: string }, b: { owner: string }) =>
      //   a.owner > b.owner,
      sorter: (a: { owner: string }, b: { owner: string }) =>
        a.owner > b.owner ? 1 : -1,
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '类型',
      key: 'field',
      dataIndex: 'field',
      scopedSlots: { customRender: 'field' },
      // sorter: (a: { name: string }, b: { name: string }) =>
      //   a.name > b.name,
      sorter: (
        a: { field: string; relatedAlgo: string },
        b: { field: string; relatedAlgo: string }
      ) =>
        `${a.field}-${a.relatedAlgo}` > `${b.field}-${b.relatedAlgo}` ? 1 : -1,
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModify',
      key: 'gmtModify',
      defaultSortOrder: 'descend',
      sorter: (a: { gmtModify: string }, b: { gmtModify: string }) =>
        Date.parse(a.gmtModify) - Date.parse(b.gmtModify),
    },
    {
      title: '状态',
      key: 'trainStatus',
      dataIndex: 'trainStatus',
      scopedSlots: { customRender: 'trainStatus' },
    },
    {
      title: '训练时长',
      key: 'runTime',
      dataIndex: 'runTime',
      scopedSlots: { customRender: 'runTime' },
      defaultSortOrder: 'descend',
      sortDirections: ['descend', 'ascend'],
      sorter: (a: { runTime: any }, b: { runTime: any }) =>
        a.runTime > b.runTime ? 1 : -1,
    },
    {
      title: '操作',
      key: 'operate',
      scopedSlots: { customRender: 'action' },
    },
  ]
  public modelList: any = []
  public modelList2: any = []
  public applyType: string = 'applied'
  public tableLoading: boolean = false
  public localPanel: any = []
  public localPlugins: any = []
  public panelLoading: boolean = false
  public queryFm: any = {
    whereValue: undefined,
    type: '',
    // orderKey:'public_time',
    // order:'desc'
  }
  public pageIndex: number = 1
  public pageSize: number = 10
  public totalElements: number = 0
  public visionVisible: boolean = false
  public viewId: number = 0
  public timeout: any = {}
  public deleteItem: any = {}
  public uninstallVisible: boolean = false
  public projects: any = []
  public defaulCover: any = require('@/assets/default.png')

  public get updateState() {
    return DataViewStore.operateModel
  }

  @Watch('updateState', { deep: true, immediate: true })
  public modelChange() {
    if (this.updateState && this.updateState.type === 'local') {
      this.queryLocalList()
    }
  }

  @Watch('applyType')
  public queryListByStatus() {
    this.queryFm.status = '5'
    this.queryLocalList()
  }

  public pageChange(page: number, pageSize: number) {
    window.scrollTo(0, 0)
    this.pageIndex = page
    this.pageSize = pageSize
    this.queryLocalList()
  }

  public pageSizeChange(current: number, size: number) {
    window.scrollTo(0, 0)
    this.pageIndex = current
    this.pageSize = size
    this.queryLocalList()
  }

  @Watch('tab')
  public tabChange() {
    if (this.tab === '1') {
      this.searchClick()
    }
  }

  @Watch('field')
  public initList() {
    this.queryFm.field = this.field
    this.queryLocalList()
  }

  @Watch('whereValue')
  public initList2() {
    this.queryFm.whereValue = this.whereValue
    this.queryLocalList()
  }

  public created() {
    this.queryLocalList()
    // window.addEventListener('keyup', this.globalKeyUp)
  }

  public beforeDestroy() {
    // document.removeEventListener('keyup', this.globalKeyUp)
  }

  public customRow(record: any) {
    return {
      on: {
        click: () => {
          if (record.type === 1) {
            this.$router.push(
              `/management/plugin/algorithm?id=${record.id}&tab=1`
            )
          } else {
            this.$router.push(`/management/plugin/detail?id=${record.id}&tab=1`)
          }
        },
      },
    }
  }

  public searchClick() {
    // 从首页开始查询
    this.pageIndex = 1
    this.pageSize = 10
    this.queryLocalList()
  }

  public smartQuery() {
    if (this.timeout) {
      clearTimeout(this.timeout)
    }
    this.timeout = setTimeout(() => this.searchClick(), 300)
  }

  public async queryLocalList() {
    this.tableLoading = true
    try {
      const response = await queryLocalModel({
        data: {
          ...this.queryFm,
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
        },
      })
      this.tableLoading = false
      if (response.data.code === 100) {
        this.localPlugins = response.data.result.data
        this.pageIndex = response.data.result.pageIndex
        this.pageSize = response.data.result.pageSize
        this.totalElements = response.data.result.totalElements
      } else {
        this.$message.error(response.data.message)
      }
    } catch {
      this.tableLoading = false
    }
  }

  public async searchModel(modelName: any) {
    // type=1 local
    if (this.queryFm.whereValue) {
      this.$set(
        this.queryFm,
        'whereValue',
        `${this.queryFm.whereValue},${modelName}`
      )
    } else {
      this.$set(this.queryFm, 'whereValue', modelName)
    }
    this.queryLocalList()
  }

  public viewModelDetail(id: any) {
    this.$router.push({ path: `/management/plugin/detail?id=${id}` })
  }

  public async uninstal(record: any) {
    this.deleteItem = record
    // 检查是否可卸载
    const response1 = await queryProjectUsed({
      data: { modelId: record.modelId },
    })
    if (response1.data.code === 100) {
      this.projects = response1.data.result
      if (this.projects.length > 0) {
        this.uninstallVisible = true
      } else {
        const response = await deleteLocalModel({ data: { id: record.id } })
        if (response.data.code === 100) {
          this.$message.success('卸载成功！')
          this.queryLocalList()
          this.$emit('update-panel')
        } else {
          this.$message.error(response.data.message)
        }
      }
    } else {
      this.$message.error(response1.data.message)
    }
  }

  public async viewVisions(record: any) {
    this.visionVisible = true
    this.viewId = record.id
  }

  public globalKeyUp($event: any) {
    console.log('local', this.tab)
    if ($event.key === 'Enter' && this.tab === '1') {
      this.queryLocalList()
    }
  }
}
</script>

<style lang="less" scoped>
@import '@/constants';
@import '@/styles/scroll-bar';

.plugin-content {
  // height: calc(100vh - 185px);
  height: 100%;
  overflow-y: auto;
  width: 100%;

  .fixed-tool {
    align-items: center;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.08);
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 1px;
    min-width: 824px;
    padding: 24px 0;
    width: 100%;

    .input-group {
      max-width: 80%;

      .search-input {
        width: calc(100% - 100px);
      }
    }

    .select-field {
      background-color: #f5f5f5;
      padding: 12px;
      width: 80%;
    }

    .sort {
      // position: absolute;
      // right:177px;
      margin-left: 32px;
      min-width: 280px;

      .selector2 {
        margin-left: 8px;
        min-width: 110px;
      }

      .selector3 {
        margin-left: 8px;
        width: 80px;
      }
    }

    .view-jianwei {
      position: absolute;
      right: 32px;
    }
  }

  .pagination {
    background: #fff;
    padding-top: 24px;
    text-align: right;
  }

  .btns {
    margin-bottom: 12px;
    position: relative;
  }

  .left-space {
    margin-left: 12px;
  }

  .cell-detail {
    align-items: center;
    display: flex;
    margin: 0;

    .icon {
      height: 60px;
      margin-right: 12px;
      // font-size: 60px;
      width: 60px;
    }
  }

  .title {
    align-items: center;
    display: flex;

    .icon {
      font-size: 16px;
      margin-right: 5px;
    }
  }
}
</style>
